from time import sleep

from PIL import Image
from lxml import etree
from selenium.webdriver import ActionChains

from lib.sys.logger_factory import LoggerFactory
from lib.sys.sys_config import SystemConfig
from crawler_core.constant.constants import Constants
from crawler_core.driver.driver_proxy import DriverProxy
from crawler_core.exception.aoount_exec import AccountException
from crawler_core.exception.vertify_exec import VertifyException
from login_server.utils.vertify_code_utils import VertifyCodeUtils
from login_server.interface_login import LoginInterface
from login_server.template.template_51job import Property51job


class LoginJob51(LoginInterface):
    logger = LoggerFactory.getLogger("LoginJob51", "login")

    def __init__(self):
        pass

    def login(self, context):
        self.driver = DriverProxy().get()
        self.username = context[Constants.CONTEXT_USERNAME]
        self.password = context[Constants.CONTEXT_PASSWORD]
        self.account = context[Constants.CONTEXT_ACCOUNT]

        if self.driver:
            try:
                cookies_raws = self.doLogin()
                dict_raw = {}
                for cookie_raw in cookies_raws:
                    dict_raw[cookie_raw['name']] = cookie_raw['value']
                cookies = []
                for cookie in dict_raw.items():
                    dict = {}
                    dict["name"] = cookie[0]
                    dict["value"] = cookie[1]
                    cookies.append(dict)
            except VertifyException:
                raise VertifyException()
            except AccountException:
                raise AccountException()
            finally:
                self.driver.close()
        return cookies

    def doLogin(self):

        self.start()
        try:
            self.validate()
        except VertifyException:
            LoginJob51.logger.error("LoginJob51登录失败，验证码失败...")
            raise VertifyException()
        except AccountException:
            LoginJob51.logger.error("LoginJob51登录失败, 账号密码有误...")
            raise AccountException()
        return self.driver.get_cookies()

    def start(self):
        self.driver.maximize_window()
        self.driver.get(Property51job.login_url)
        sleep(3)
        self.driver.find_element_by_xpath(Property51job.input_account).send_keys(self.account)
        self.driver.find_element_by_xpath(Property51job.input_username).send_keys(self.username)
        self.driver.find_element_by_xpath(Property51job.input_password).send_keys(self.password)
        sleep(2)
        self.driver.find_element_by_xpath(Property51job.input_code).click()
        sleep(5)

    def validate(self):
        self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        image_path = SystemConfig.get_p_screen_image_path()
        self.driver.save_screenshot(image_path + '/image_51job.png')
        sleep(3)
        catch_greest = self.driver.find_element_by_xpath("//div[@class='yz-main']")
        width = catch_greest.size["width"]
        height = catch_greest.size['height']
        LoginJob51.logger.info("LoginJob51 图片解码宽高 [w,h]: %s, %s" % (width, height))
        point_x = catch_greest.location["x"]
        point_y = catch_greest.location["y"] - Property51job.position_y
        LoginJob51.logger.info("LoginJob51 图片解码坐标 [x,y]: %s, %s" % (point_x, point_y))

        elementwidth = point_x + catch_greest.size["width"]
        elementheight = point_y + catch_greest.size["height"] - Property51job.position_h
        picture = Image.open(image_path + '/image_51job.png')
        imgFrame = picture.crop((point_x, point_y, elementwidth, elementheight))
        imgFrame.save(image_path + '/image_51job2.png')
        im = open(image_path + '/image_51job2.png', 'rb').read()
        xy = VertifyCodeUtils.analysis(im, 9004)
        locations = xy["pic_str"].split("|")
        LoginJob51.logger.info("LoginJob51 图片解码 location: %s" % str(locations))

        location_x1, location_y1 = locations[0].split(",")
        x1 = int(location_x1)
        y1 = int(location_y1)
        sleep(1)
        ActionChains(self.driver).move_to_element_with_offset(catch_greest, xoffset=x1, yoffset=y1).click().perform()
        location_x2, location_y2 = locations[1].split(",")
        x2 = int(location_x2)
        y2 = int(location_y2)
        sleep(1)
        ActionChains(self.driver).move_to_element_with_offset(catch_greest, xoffset=x2, yoffset=y2).click().perform()

        location_x3, location_y3 = locations[2].split(",")
        x3 = int(location_x3)
        y3 = int(location_y3)
        sleep(1)
        ActionChains(self.driver).move_to_element_with_offset(catch_greest, xoffset=x3, yoffset=y3).click().perform()
        location_x4, location_y4 = locations[3].split(",")
        x4 = int(location_x4)
        y4 = int(location_y4)
        sleep(1)
        ActionChains(self.driver).move_to_element_with_offset(catch_greest, xoffset=x4, yoffset=y4).click().perform()
        sleep(1)
        self.driver.save_screenshot(image_path + '/image_51job3.png')
        self.driver.find_element_by_xpath(Property51job.btnValidate).click()
        sleep(3)
        self.driver.save_screenshot(image_path + '/image_51job4.png')
        try:
            self.driver.find_element_by_xpath(Property51job.login_btnLoginCN).click()
        except BaseException:
            raise VertifyException()
        self.driver.save_screenshot(image_path + '/image_51job5.png')

        html_web = etree.HTML(self.driver.page_source)
        error = "".join(html_web.xpath("//div[@id='errOther']/a/text()"))
        if error:
            # 判断 账号或者 验证码
            if "验证码" in error:
                raise VertifyException()
            else:
                raise AccountException()
        else:
            pass
        sleep(2)
        try:
            self.driver.find_element_by_xpath(Property51job.gvOnLineUser).click()
        except:
            pass
